﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenFTP;
using System.IO;
namespace 文件传PDA工具
{
    public partial class ProgressForm : Form
    {
        private DataRow 参数 { get; set; }
        private string 读取参数内容(string 参数项目)
        {
            if (!参数.Table.Columns.Contains(参数项目))
                return string.Empty;
            return 参数[参数项目].ToString();
        }
        private bool 读取参数开关(string 参数项目)
        {
            if (!参数.Table.Columns.Contains(参数项目))
                return false;
            return YZZ.Tools.StringToBool(参数[参数项目].ToString());
        }
        //private string _Server { get; set; }
        //private string _Port { get; set; }
        //private string _UserName { get; set; }
        //private string _PassWord { get; set; }
        private string _Folder = string.Empty; /*{ get; set; }*/
        //private bool _ClearOldDB { get; set; }
        //private bool _UpLoadWince { get; set; }
        //private bool _UpLoadXmlce { get; set; }
        //private bool _UpLoadPrint { get; set; }
        //private bool _UpLoadInfo { get; set; }
        private bool Done { get; set; }
        //private int WaitTime { get; set; }
        public ProgressForm(DataRow 参数)
        {
            InitializeComponent();
            进度条.Maximum = 1000;
            进度条.Minimum = 0;
            进度条.Step = 10;
            this.参数 = 参数;
            //WaitTime = 0;
            //_Server = Server;
            //_Port = Port;
            //_UserName = UserName;
            //_PassWord = PassWord;
            _Folder = 读取参数内容("文件夹");

            //_ClearOldDB = ClearOldDB;
            //_UpLoadWince = UpLoadWince;
            //_UpLoadXmlce = UpLoadXmlce;
            //_UpLoadPrint = UpLoadPrint;
            //_UpLoadInfo = UpLoadInfo;
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;
            //输出框.Enabled = false;
            输出框.ReadOnly = true;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            ////输出框.Text += "\r\n" + NowTime.ToString();
            //输出框.Select(输出框.Text.Length, 0);
            //输出框.ScrollToCaret();
            ////NowTime++;
            //进度条.PerformStep();
            //if (进度条.Value == 进度条.Maximum)
            //{
            //    WaitTime++;
            //}
            //if (WaitTime > 30)
            //{
            //    timer1.Stop();
            //    返回按钮.Text = "完成(&C)";
            //    Done = true;
            //}
        }

        private void 返回按钮_Click(object sender, EventArgs e)
        {
            if (Done)
            {
                this.DialogResult = DialogResult.OK;
            }
            if (backgroundWorker1.WorkerSupportsCancellation == true)
            {
                // 取消异步操作
                backgroundWorker1.CancelAsync();
            }
            this.DialogResult = DialogResult.Cancel;
        }

        private void ProgressForm_Load(object sender, EventArgs e)
        {
            Done = false;
            if (backgroundWorker1.IsBusy != true)
            {
                // 启动异步操作
                backgroundWorker1.RunWorkerAsync();
            }
        }
        private void 输出文字(string 内容, bool 换行 = true)
        {
            输出框.Invoke(new EventHandler(delegate
            {
                if (!string.IsNullOrEmpty(输出框.Text) && 换行)
                    输出框.Text += "\r\n";
                输出框.Text += 内容;
                输出框.Select(输出框.Text.Length, 0);
                输出框.ScrollToCaret();
            }));
        }
        private void 发布一个文件(bool 判断, string 文件名, string 文件夹,string 文件夹名, ref int 进度)
        {
            if (!判断)
            {
                backgroundWorker1.ReportProgress(进度 + (int)(0.007 * 100));
                return;
            }
            //if (string.IsNullOrEmpty(文件夹) || !YZZ.FileHelperTemplate.HasFile(文件夹))
            //{
            //    输出文字("未能找到" + 文件夹 + "……已跳过！");
            //    backgroundWorker1.ReportProgress(进度 + (int)(0.007 * 100));
            //    return;
            //}
            if (!YZZ.FileHelperTemplate.HasFile(Path.GetFileName(文件名)))
            {
                输出文字("未能找到" + 文件名 + "……已跳过！");
                backgroundWorker1.ReportProgress(进度 + (int)(0.007 * 100));
                return;
            }

            try
            {
                输出文字("正在发布" + 文件名 + "到" + 文件夹名 + "……");
                YZZ.FileHelperTemplate.CopyFile(System.Environment.CurrentDirectory + "\\" + 文件名, 文件夹 + "\\" + 文件名);
                输出文字("发布成功！", false);
            }
            catch
            {
                输出文字("发布失败，请检查文件夹是否正确！", false);
            }
            backgroundWorker1.ReportProgress(进度 + (int)(0.007 * 100));
        }
        private void 处理一项上传(OpenFTP.FTP f,bool 判断,string 文件名,ref  int 进度)
        {
            if (判断)
            {
                if (YZZ.FileHelperTemplate.HasFile(Path.GetFileName(文件名)))
                {
                    输出文字("正在删除原" + 文件名 + "文件……");
                    try { f.Files.RemoveFile(文件名); } catch { }
                    输出文字("删除完成！", false);
                    int iProgress = 进度 + (int)(0.015 * 100);
                    backgroundWorker1.ReportProgress(iProgress);
                    输出文字("正在上传新" + 文件名 + "文件……");
                    f.Files.Upload(Path.GetFileName(文件名), Path.GetFileName(文件名));
                    while (!f.Files.UploadComplete)
                    {
                        iProgress = 进度 + (int)(0.015 * 100) + ((int)(((double)f.Files.PercentComplete) * 0.05));
                        backgroundWorker1.ReportProgress(iProgress);
                    }
                    输出文字("上传完成！", false);
                }
                else
                {
                    输出文字("本地文件" + 文件名 + "未找到……已跳过！", false);
                    int iProgress = 进度 + ((int)(0.07 * 100));
                    backgroundWorker1.ReportProgress(iProgress);
                }

            }
            else
            {
                int iProgress = 进度 + ((int)(0.07 * 100));
                backgroundWorker1.ReportProgress(iProgress);
            }
            进度 += ((int)(0.07 * 100));
        }
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            //for (int i = 1; i <= 10; i++)
            {
                if (backgroundWorker1.CancellationPending == true)
                {
                    e.Cancel = true;
                    return;
                }
                else
                {
                    try
                    {
                        int Progress = 0;
                        if (读取参数开关("传PDA"))
                        {
                            输出文字("正在连接PDA的文件服务……");
                            OpenFTP.FTP f = new OpenFTP.FTP();
                            f.Connect(读取参数内容("服务器") + ":" + 读取参数内容("端口"), 读取参数内容("账号"), 读取参数内容("密码"), true);
                            输出文字("连接完成！", false);
                            if (_Folder.Substring(0, 1) != "/")
                                _Folder = "/" + _Folder;
                            if (_Folder.Substring(_Folder.Length - 2, 1) != "/")
                                _Folder = _Folder + "/";
                            //if (_Folder.Contains(" "))
                            //    _Folder = "\"" + _Folder + "\"";
                            f.ChangeDirectory(_Folder);

                            if (读取参数开关("清理数据备份"))
                            {
                                输出文字("正在清理旧数据文件……");
                                try { f.Files.RemoveFile("xmlce.bk"); } catch { }
                                Progress += (int)(0.03 * 100);
                                backgroundWorker1.ReportProgress(Progress);
                                try { f.Files.RemoveFile("Error_Log.db"); } catch { }
                                Progress += (int)(0.03 * 100);
                                backgroundWorker1.ReportProgress(Progress);
                                输出文字("清理完成！", false);
                            }
                            else
                            {
                                Progress += (int)(0.03 * 100);
                                backgroundWorker1.ReportProgress(Progress);
                                Progress += (int)(0.03 * 100);
                                backgroundWorker1.ReportProgress(Progress);
                            }
                            处理一项上传(f, 读取参数开关("上传wince"), "wince.db", ref Progress);
                            处理一项上传(f, 读取参数开关("上传xmlce"), "xmlce.db", ref Progress);
                            处理一项上传(f, 读取参数开关("上传print"), "print.db", ref Progress);
                            处理一项上传(f, 读取参数开关("上传info"), "info.db", ref Progress);

                            f.Disconnect();
                            f = null;

                        }
                        else
                        {
                            Progress += (int)(0.3 * 100);
                            backgroundWorker1.ReportProgress(Progress);
                        }
                        if (读取参数开关("发布测试版"))
                        {
                            发布一个文件(读取参数开关("上传wince"), "wince.db", 读取参数内容("测试版文件夹"), "测试版文件夹", ref Progress);
                            发布一个文件(读取参数开关("上传xmlce"), "xmlce.db", 读取参数内容("测试版文件夹"), "测试版文件夹", ref Progress);
                            发布一个文件(读取参数开关("上传print"), "print.db", 读取参数内容("测试版文件夹"), "测试版文件夹", ref Progress);
                            发布一个文件(读取参数开关("上传info"), "info.db", 读取参数内容("测试版文件夹"), "测试版文件夹", ref Progress);
                        }
                        else
                        {
                            Progress += (int)(0.3 * 100);
                            backgroundWorker1.ReportProgress(Progress);
                        }
                        if (读取参数开关("发布正式版"))
                        {
                            发布一个文件(读取参数开关("上传wince"), "wince.db", 读取参数内容("正式版文件夹"), "正式版文件夹", ref Progress);
                            发布一个文件(读取参数开关("上传xmlce"), "xmlce.db", 读取参数内容("正式版文件夹"), "正式版文件夹", ref Progress);
                            发布一个文件(读取参数开关("上传print"), "print.db", 读取参数内容("正式版文件夹"), "正式版文件夹", ref Progress);
                            发布一个文件(读取参数开关("上传info"), "info.db", 读取参数内容("正式版文件夹"), "正式版文件夹", ref Progress);
                        }
                        else
                        {
                            Progress += (int)(0.3 * 100);
                            backgroundWorker1.ReportProgress(Progress);
                        }
                        if (读取参数开关("测试版转正式"))
                        {
                            
                            {
                                string 文件名 = string.Empty;
                                输出文字("正在发布正式版apk……");
                                string[] 文件列表 = YZZ.FileHelperTemplate.ListDirectoryFiles(读取参数内容("测试版文件夹"));
                                int count = 0;
                                
                                foreach (string 文件 in 文件列表)
                                {
                                    string[] 文件路径分析 = 文件.Split('\\');
                                    string 纯文件名 = 文件路径分析[文件路径分析.Length - 1];
                                    string 扩展名 = 纯文件名.Substring(纯文件名.LastIndexOf('.'), 纯文件名.Length - 纯文件名.LastIndexOf('.'));
                                    if (!string.IsNullOrEmpty(扩展名) && 扩展名.ToLower() == ".apk")
                                    {
                                        count++;
                                        文件名 = 纯文件名;
                                    }
                                }
                                if (count > 1)
                                {
                                    输出文字("测试文件夹中发现超过1个apk文件，发布失败！", false);
                                    输出文字("请确保测试文件夹中只有一个apk文件并再试一次。");

                                }
                                else
                                {
                                    YZZ.FileHelperTemplate.CopyFile(读取参数内容("测试版文件夹") + "\\" + 文件名, 读取参数内容("正式版文件夹") + "\\" + 文件名);
                                    输出文字("发布完成！", false);
                                }
                            }
                            
                        }
                        if (Progress < 100)
                            Progress = 100;
                        backgroundWorker1.ReportProgress(Progress);
                    }
                    catch (Exception 错误信息)
                    {
                        输出文字("发生错误:" + 错误信息.Message);
                        //MessageBox.Show(错误信息.Message, "错误！",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    }
                }
            }

           
        }

        private void backgroudWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //输出框.Text += "\r\n" + NowTime.ToString();
            输出框.Select(输出框.Text.Length, 0);
            输出框.ScrollToCaret();
            //NowTime++;
            进度条.Value = e.ProgressPercentage * 10;
            if (进度条.Value == 进度条.Maximum)
            {
                //timer1.Stop();

            }
        }
        private void backgroundWorker1_RunWorkerComplete(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled == true)
            {
                MessageBox.Show("任务已取消！", "取消");
            }
            else if (e.Error != null)
            {
                MessageBox.Show( e.Error.Message,"错误");
            }
            else
            {
                返回按钮.Text = "完成(&C)";
                Done = true;
            }
        }

    }
}
